package com.michaelwolf.mytool.ruwlsr;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JobFinder {
	
	private String wcfbaseDir;
	private List<JobInfo> jobInfoList = new ArrayList<JobInfo>();

	public void setWcfbaseDir(String wcfbaseDir) {
		this.wcfbaseDir = wcfbaseDir;
	}

	public List<JobInfo> findJob() throws IOException {
		File baseDir = new File(wcfbaseDir);
		if(!baseDir.exists()){
			throw new IOException("wcf base Directory do not exist");
		}
		
		traverse(baseDir);
		
		
		return jobInfoList;
	}

	private void traverse(File file) {
		// TODO Auto-generated method stub
		if(isModuleDir(file)){
			JobInfo jobInfo = createJobInfo(file.getAbsolutePath());
			jobInfoList.add(jobInfo);
		}else if(file.isDirectory()){
			File[] subDirList = file.listFiles();
			for(File subDir : subDirList){
				traverse(subDir);
			}
		}
		
		
	}

	private boolean isModuleDir(File file) {
		if(!file.isDirectory()){
			return false;
		}
		
		File[] subFilesOrDirs = file.listFiles();
		
		for(File subFileOrDir : subFilesOrDirs){
			if(subFileOrDir.isFile() && subFileOrDir.getName().equals("wcf.xml")){
				return true;
			}
		}
		
		return false;
	}

	private JobInfo createJobInfo(String modulePath) {
		String moduleName = modulePath.substring(modulePath.lastIndexOf(File.separator) + 1, modulePath.length());
		
		return new JobInfo(modulePath, moduleName);
	}

	public static JobFinder createJobFinder(String wcfbaseDir) {
		JobFinder jobFinder = new JobFinder();
		jobFinder.setWcfbaseDir(wcfbaseDir);
		
		return jobFinder;
	}

}
